<?php

/**
 *	Class Doctors
 *  --------------
 *	Description : encapsulates methods and properties
 *	Written by  : ApPHP
 *  Updated	    : 26.01.2012
 *  Usage       : Medical Appointment
 *
 *	PUBLIC:				  	STATIC:				 	PRIVATE:
 * 	------------------	  	---------------     	---------------
 *	__construct             GetAllActive
 *	__destruct              GetDoctorInfoBySchedule
 *	AfterDeleteRecord		GetDoctorInfoById
 *	                        DrawAppointmentsBlock
 *	                        SearchFor
 *	                        DrawSearchResult
 *	                        DrawDoctorInfo
 *	                        GetDoctorSpecialities
 *	                        GetDoctorSpeciality
 *	
 *  1.0.0
 *      - added SearchFor
 *      - added DrawSearchResult
 *      -
 *      -
 *      -
 *      
 **/


class Doctors extends MicroGrid {
	
	protected $debug = false;
	
	// #001 private $arrTranslations = '';
	private $currency_format = '';
	
	//==========================================================================
    // Class Constructor
	//==========================================================================
	function __construct()
	{		
		parent::__construct();
		
		$this->params = array();
		
		## for standard fields
		if(isset($_POST['first_name']))  $this->params['first_name'] = prepare_input($_POST['first_name']);
		if(isset($_POST['middle_name'])) $this->params['middle_name'] = prepare_input($_POST['middle_name']);
		if(isset($_POST['last_name']))   $this->params['last_name'] = prepare_input($_POST['last_name']);
		if(isset($_POST['gender']))      $this->params['gender'] = prepare_input($_POST['gender']);
		if(isset($_POST['birth_date']))  $this->params['birth_date'] = prepare_input($_POST['birth_date']);
		if(isset($_POST['title']))       $this->params['title'] = prepare_input($_POST['title']);
		if(isset($_POST['medical_degree'])) $this->params['medical_degree'] = prepare_input($_POST['medical_degree']);
		if(isset($_POST['education']))   $this->params['education'] = prepare_input($_POST['education']);
		if(isset($_POST['hospital_affiliations']))   $this->params['hospital_affiliations'] = prepare_input($_POST['hospital_affiliations']);
		if(isset($_POST['board_certifications']))    $this->params['board_certifications'] = prepare_input($_POST['board_certifications']);
		if(isset($_POST['awards_and_publications'])) $this->params['awards_and_publications'] = prepare_input($_POST['awards_and_publications']);
		if(isset($_POST['languages_spoken'])) $this->params['languages_spoken'] = prepare_input($_POST['languages_spoken']);
		if(isset($_POST['insurances_accepted'])) $this->params['insurances_accepted'] = prepare_input($_POST['insurances_accepted']);
		if(isset($_POST['work_phone'])) $this->params['work_phone'] = prepare_input($_POST['work_phone']);
		if(isset($_POST['work_mobile_phone'])) $this->params['work_mobile_phone'] = prepare_input($_POST['work_mobile_phone']);
		if(isset($_POST['default_visit_price'])) $this->params['default_visit_price'] = prepare_input($_POST['default_visit_price']);
		if(isset($_POST['default_visit_duration'])) $this->params['default_visit_duration'] = prepare_input($_POST['default_visit_duration']);

		
		## for checkboxes 
		$this->params['is_active'] = isset($_POST['is_active']) ? prepare_input($_POST['is_active']) : '0';

		## for images (not necessary)
		//if(isset($_POST['icon'])){
		//	$this->params['icon'] = prepare_input($_POST['icon']);
		//}else if(isset($_FILES['icon']['name']) && $_FILES['icon']['name'] != ''){
		//	// nothing 			
		//}else if (self::GetParameter('action') == 'create'){
		//	$this->params['icon'] = '';
		//}

		## for files:
		// define nothing

		$this->params['language_id'] = '';//MicroGrid::GetParameter('language_id');
	
		//$this->uPrefix 		= 'prefix_';
		
		$this->primaryKey 	= 'id';
		$this->tableName 	= TABLE_DOCTORS;
		$this->dataSet 		= array();
		$this->error 		= '';
		$this->formActionURL = 'index.php?admin=doctors_management';
		$this->actions      = array('add'=>true, 'edit'=>true, 'details'=>true, 'delete'=>true);
		$this->actionIcons  = true;
		$this->allowRefresh = true;
		$this->allowTopButtons = true;
		$this->alertOnDelete = ''; // leave empty to use default alerts

		$this->allowLanguages = false;
		$this->languageId  	= ''; //($this->params['language_id'] != '') ? $this->params['language_id'] : Languages::GetDefaultLang();
		$this->WHERE_CLAUSE = ''; // WHERE .... / 'WHERE language_id = \''.$this->languageId.'\'';				
		$this->ORDER_CLAUSE = ''; // ORDER BY '.$this->tableName.'.date_created DESC
		
		$this->isAlterColorsAllowed = true;

		$this->isPagingAllowed = true;
		$this->pageSize = 20;

		$this->isSortingAllowed = true;

		$this->isExportingAllowed = true;
		$this->arrExportingTypes = array('csv'=>true);
		
		// define filtering fields
		$this->isFilteringAllowed = true;		
		$this->arrFilteringFields = array(
			_NAME  => array('table'=>TABLE_DOCTORS, 'field'=>'last_name', 'type'=>'text', 'sign'=>'like%', 'width'=>'110px', 'visible'=>true),
			// 'Caption_2'  => array('table'=>'', 'field'=>'', 'type'=>'dropdownlist', 'source'=>array(), 'sign'=>'=|like%|%like|%like%', 'width'=>'130px', 'visible'=>true),
		);

		$date_format = get_date_format('view');
		$date_format_edit = get_date_format('edit');
		///$datetime_format = get_datetime_format();
		
		$this->currency_format = get_currency_format();
		$pre_currency_symbol = ((Application::Get('currency_symbol_place') == 'left') ? Application::Get('currency_symbol') : '');
		$post_currency_symbol = ((Application::Get('currency_symbol_place') == 'right') ? Application::Get('currency_symbol') : '');

		// prepare languages array		
		/// $total_languages = Languages::GetAllActive();
		/// $arr_languages      = array();
		/// foreach($total_languages[0] as $key => $val){
		/// 	$arr_languages[$val['abbreviation']] = $val['lang_name'];
		/// }
		
		$arr_genders = array('f'=>_FEMALE, 'm'=>_MALE);
		$arr_activity = array('0'=>'<span class=no>'._NO.'</span>', '1'=>'<span class=yes>'._YES.'</span>');
		$arr_titles	= array('Mr.'=>'Mr.', 'Ms.'=>'Ms.', 'Mrs.'=>'Mrs.', 'Miss'=>'Miss');
		$arr_degrees = array('BMBS'=>'BMBS', 'MBBS'=>'MBBS', 'MBChB'=>'MBChB', 'MB BCh'=>'MB BCh', 'BMed'=>'BMed', 'MD'=>'MD', 'MDCM'=>'MDCM', 'Dr.MuD'=>'Dr.MuD', 'Dr.Med'=>'Dr.Med', 'Cand.med'=>'Cand.med', 'Med'=>'Med');
		$arr_slots = get_time_slots();

		///////////////////////////////////////////////////////////////////////////////
		// #002. prepare translation fields array
		/// $this->arrTranslations = $this->PrepareTranslateFields(
		///	array('field1', 'field2')
		/// );
		///////////////////////////////////////////////////////////////////////////////			

		///////////////////////////////////////////////////////////////////////////////			
		// #003. prepare translations array for add/edit/detail modes
		/// $sql_translation_description = $this->PrepareTranslateSql(
		///	TABLE_XXX_DESCRIPTION,
		///	'gallery_album_id',
		///	array('field1', 'field2')
		/// );
		///////////////////////////////////////////////////////////////////////////////			

		//---------------------------------------------------------------------- 
		// VIEW MODE
		// format: strip_tags
		// format: nl2br
		// format: 'format'=>'date', 'format_parameter'=>'M d, Y, g:i A'
		// format: 'format'=>'currency', 'format_parameter'=>'european|2' or 'format_parameter'=>'american|4'
		//---------------------------------------------------------------------- 
		$this->VIEW_MODE_SQL = 'SELECT '.$this->primaryKey.',
									first_name,
									middle_name,
									last_name,
									CONCAT(first_name, " ", middle_name, " ", last_name) as full_name,
									gender,
									birth_date,
									title,
									medical_degree,
									education,
									residency_training,
									hospital_affiliations,
									board_certifications,
									awards_and_publications,
									languages_spoken,
									insurances_accepted,
									IF(doctor_photo <> "", doctor_photo, IF(gender = "f", "doctor_f.png", "doctor_m.png")) as doctor_photo,
									doctor_photo_thumb,
									work_phone,
									work_mobile_phone,
									CONCAT(work_phone, "<br>", work_mobile_phone) as mod_phones,
									default_visit_price,
									default_visit_duration,
									is_active,
									"[ '._SCHEDULES.' ]" as link_schedules,
									"[ '._TIMEOFF.' ]" as link_timeoffs,
									CONCAT("[ '._SPECIALITIES.' ]", " (", (SELECT COUNT(*) FROM '.TABLE_DOCTORS_SPECIALITIES.' ds WHERE ds.doctor_id = '.$this->tableName.'.id), ")") as link_specialities
								FROM '.$this->tableName;		
		// define view mode fields
		$this->arrViewModeFields = array(
			'doctor_photo'      => array('title'=>_PHOTO, 'type'=>'image', 'align'=>'center', 'width'=>'44px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'image_width'=>'38px', 'image_height'=>'32px', 'target'=>'images/doctors/', 'no_image'=>'no_image.png'),
			'full_name'         => array('title'=>_NAME, 'type'=>'label', 'align'=>'left', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),			
			'mod_phones'        => array('title'=>_PHONES, 'type'=>'label', 'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>''),			
			'medical_degree'    => array('title'=>_DEGREE, 'type'=>'enum',  'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'source'=>$arr_degrees),
			'is_active'         => array('title'=>_ACTIVE, 'type'=>'enum',  'align'=>'center', 'width'=>'', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'source'=>$arr_activity),
			'link_specialities' => array('title'=>'', 'type'=>'link',  'align'=>'center', 'width'=>'120px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>'', 'href'=>'index.php?admin=doctors_specialities&doctor_id={id}', 'target'=>''),
			'link_schedules'    => array('title'=>'', 'type'=>'link',  'align'=>'center', 'width'=>'110px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>'', 'href'=>'index.php?admin=schedules_management&doc_id={id}', 'target'=>''),
			'link_timeoffs'     => array('title'=>'', 'type'=>'link',  'align'=>'center', 'width'=>'90px', 'sortable'=>true, 'nowrap'=>'', 'visible'=>'', 'tooltip'=>'', 'maxlength'=>'', 'format'=>'', 'format_parameter'=>'', 'href'=>'index.php?admin=timeoff_management&doc_id={id}', 'target'=>''),
		);
		
		//---------------------------------------------------------------------- 
		// ADD MODE
		// - Validation Type: alpha|numeric|float|alpha_numeric|text|email|ip_address|password|date
		// 	 Validation Sub-Type: positive (for numeric and float)
		//   Ex.: 'validation_type'=>'numeric', 'validation_type'=>'numeric|positive'
		// - Validation Max Length: 12, 255... Ex.: 'validation_maxlength'=>'255'
		// - Validation Min Length: 4, 6... Ex.: 'validation_minlength'=>'4'
		// - Validation Max Value: 12, 255... Ex.: 'validation_maximum'=>'99.99'
		//---------------------------------------------------------------------- 
		// define add mode fields
		$this->arrAddModeFields = array(		    
			'separator_account_info' => array(
				'separator_info' => array('legend'=>_ACCOUNT_DETAILS),
				'doctor_photo' => array('title'=>_PHOTO, 'type'=>'image',    'width'=>'210px', 'required'=>false, 'readonly'=>false, 'target'=>'images/doctors/', 'no_image'=>'no_image.png', 'random_name'=>true, 'overwrite_image'=>false, 'unique'=>false, 'thumbnail_create'=>true, 'thumbnail_field'=>'doctor_photo_thumb', 'thumbnail_width'=>'90px', 'thumbnail_height'=>'90px'),
				'work_phone'     => array('title'=>_PHONE, 'type'=>'textbox',  'width'=>'210px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'32', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'work_mobile_phone' => array('title'=>_MOBILE_PHONE, 'type'=>'textbox',  'width'=>'210px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'32', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'default_visit_price' => array('title'=>_DEFAULT_PRICE_PER_VISIT, 'type'=>'textbox',  'width'=>'90px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'10', 'default'=>'0', 'validation_type'=>'float|positive', 'unique'=>false, 'visible'=>true, 'pre_html'=>$pre_currency_symbol.' ', 'post_html'=>$post_currency_symbol),
				'default_visit_duration' => array('title'=>_DEFAULT_VISIT_DURATION, 'type'=>'enum', 'width'=>'', 'required'=>true, 'readonly'=>false, 'default'=>'15', 'source'=>$arr_slots, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'is_active'    => array('title'=>_ACTIVE, 'type'=>'checkbox', 'readonly'=>false, 'default'=>'1', 'true_value'=>'1', 'false_value'=>'0', 'unique'=>false),
			),		
			'separator_personal_info' => array(
				'separator_info' => array('legend'=>_PERSONAL_INFORMATION),
				'first_name'   => array('title'=>_FIRST_NAME, 'type'=>'textbox',  'width'=>'210px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'middle_name'  => array('title'=>_MIDDLE_NAME, 'type'=>'textbox',  'width'=>'110px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'last_name'    => array('title'=>_FIRST_NAME, 'type'=>'textbox',  'width'=>'210px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'gender'       => array('title'=>_GENDER, 'type'=>'enum', 'width'=>'', 'required'=>true, 'readonly'=>false, 'default'=>'m', 'source'=>$arr_genders, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'birth_date'   => array('title'=>_BIRTH_DATE, 'type'=>'date', 'required'=>true, 'readonly'=>false, 'unique'=>false, 'visible'=>true, 'default'=>'', 'validation_type'=>'date', 'format'=>'date', 'format_parameter'=>$date_format_edit, 'min_year'=>'90', 'max_year'=>'1'),
				'title'        => array('title'=>_TITLE, 'type'=>'enum', 'width'=>'', 'required'=>false, 'readonly'=>false, 'default'=>'', 'source'=>$arr_titles, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
			),
			'separator_professional_info' => array(
				'separator_info'        => array('legend'=>_PROFESSIONAL_INFORMATION),
				'medical_degree'        => array('title'=>_DEGREE, 'type'=>'enum', 'width'=>'', 'required'=>false, 'readonly'=>false, 'default'=>'', 'source'=>$arr_degrees, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'education'             => array('title'=>_EDUCATION, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'residency_training'    => array('title'=>_RESIDENCY_TRAINING, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'hospital_affiliations' => array('title'=>_HOSPITAL_AFFILIATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'board_certifications'  => array('title'=>_BOARD_CERTIFICATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),				
				'awards_and_publications' => array('title'=>_AWARDS_AND_PUBLICATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),				
				'languages_spoken'      => array('title'=>_LANGUAGES_SPOKEN, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'52px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'125', 'unique'=>false),				
				'insurances_accepted'   => array('title'=>_INSURANCES_ACCEPTED, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),				
			),
		);

		//---------------------------------------------------------------------- 
		// EDIT MODE
		// - Validation Type: alpha|numeric|float|alpha_numeric|text|email|ip_address|password|date
		//   Validation Sub-Type: positive (for numeric and float)
		//   Ex.: 'validation_type'=>'numeric', 'validation_type'=>'numeric|positive'
		// - Validation Max Length: 12, 255... Ex.: 'validation_maxlength'=>'255'
		// - Validation Min Length: 4, 6... Ex.: 'validation_minlength'=>'4'
		// - Validation Max Value: 12, 255... Ex.: 'validation_maximum'=>'99.99'
		//---------------------------------------------------------------------- 
		$this->EDIT_MODE_SQL = 'SELECT
								'.$this->tableName.'.'.$this->primaryKey.',
								'.$this->tableName.'.*,
								IF(doctor_photo <> "", doctor_photo, IF(gender = "f", "doctor_f.png", "doctor_m.png")) as mod_doctor_photo
							FROM '.$this->tableName.'
							WHERE '.$this->tableName.'.'.$this->primaryKey.' = _RID_';		
		// define edit mode fields
		$this->arrEditModeFields = array(
			'separator_account_info' => array(
				'separator_info' => array('legend'=>_ACCOUNT_DETAILS),
				'doctor_photo' => array('title'=>_PHOTO, 'type'=>'image',    'width'=>'210px', 'required'=>false, 'readonly'=>false, 'target'=>'images/doctors/', 'no_image'=>'no_image.png', 'random_name'=>true, 'overwrite_image'=>false, 'unique'=>false, 'thumbnail_create'=>true, 'thumbnail_field'=>'doctor_photo_thumb', 'thumbnail_width'=>'90px', 'thumbnail_height'=>'90px'),
				'work_phone'     => array('title'=>_PHONE, 'type'=>'textbox',  'width'=>'210px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'32', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'work_mobile_phone' => array('title'=>_MOBILE_PHONE, 'type'=>'textbox',  'width'=>'210px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'32', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'default_visit_price' => array('title'=>_DEFAULT_PRICE_PER_VISIT, 'type'=>'textbox',  'width'=>'90px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'10', 'default'=>'0', 'validation_type'=>'float|positive', 'unique'=>false, 'visible'=>true, 'pre_html'=>$pre_currency_symbol.' ', 'post_html'=>$post_currency_symbol),
				'default_visit_duration' => array('title'=>_DEFAULT_VISIT_DURATION, 'type'=>'enum', 'width'=>'', 'required'=>true, 'readonly'=>false, 'default'=>'15', 'source'=>$arr_slots, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'is_active'    => array('title'=>_ACTIVE, 'type'=>'checkbox', 'readonly'=>false, 'default'=>'1', 'true_value'=>'1', 'false_value'=>'0', 'unique'=>false),
			),			
			'separator_personal_info'   =>array(
				'separator_info' => array('legend'=>_PERSONAL_INFORMATION),
				'first_name'   => array('title'=>_FIRST_NAME, 'type'=>'textbox',  'width'=>'210px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'middle_name'  => array('title'=>_MIDDLE_NAME, 'type'=>'textbox',  'width'=>'110px', 'required'=>false, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'last_name'    => array('title'=>_FIRST_NAME, 'type'=>'textbox',  'width'=>'210px', 'required'=>true, 'readonly'=>false, 'maxlength'=>'70', 'default'=>'', 'validation_type'=>'', 'unique'=>false, 'visible'=>true),
				'gender'       => array('title'=>_GENDER, 'type'=>'enum', 'width'=>'', 'required'=>true, 'readonly'=>false, 'default'=>'m', 'source'=>$arr_genders, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'birth_date'   => array('title'=>_BIRTH_DATE, 'type'=>'date', 'required'=>true, 'readonly'=>false, 'unique'=>false, 'visible'=>true, 'default'=>'', 'validation_type'=>'date', 'format'=>'date', 'format_parameter'=>$date_format_edit, 'min_year'=>'90', 'max_year'=>'1'),
				'title'        => array('title'=>_TITLE, 'type'=>'enum', 'width'=>'', 'required'=>false, 'readonly'=>false, 'default'=>'', 'source'=>$arr_titles, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
			),
			'separator_professional_info'   =>array(
				'separator_info'        => array('legend'=>_PROFESSIONAL_INFORMATION),
				'medical_degree'        => array('title'=>_DEGREE, 'type'=>'enum', 'width'=>'', 'required'=>false, 'readonly'=>false, 'default'=>'', 'source'=>$arr_degrees, 'default_option'=>'', 'unique'=>false, 'javascript_event'=>''),
				'education'             => array('title'=>_EDUCATION, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'residency_training'    => array('title'=>_RESIDENCY_TRAINING, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'hospital_affiliations' => array('title'=>_HOSPITAL_AFFILIATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'board_certifications'  => array('title'=>_BOARD_CERTIFICATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),
				'awards_and_publications' => array('title'=>_AWARDS_AND_PUBLICATIONS, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),				
				'languages_spoken'      => array('title'=>_LANGUAGES_SPOKEN, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'52px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'125', 'unique'=>false),				
				'insurances_accepted'   => array('title'=>_INSURANCES_ACCEPTED, 'type'=>'textarea', 'width'=>'410px', 'required'=>false, 'height'=>'70px', 'editor_type'=>'simple', 'readonly'=>false, 'default'=>'', 'validation_type'=>'', 'validation_maxlength'=>'255', 'unique'=>false),				
			),
		);

		//---------------------------------------------------------------------- 
		// DETAILS MODE
		//----------------------------------------------------------------------
		$this->DETAILS_MODE_SQL = $this->EDIT_MODE_SQL;
		$this->arrDetailsModeFields = array(
			'separator_account_info' => array(
				'separator_info'       => array('legend'=>_ACCOUNT_DETAILS),
				'mod_doctor_photo'     => array('title'=>_PHOTO, 'type'=>'image', 'target'=>'images/doctors/', 'no_image'=>'no_image.png', 'image_width'=>'90px', 'image_height'=>'90px'),
				'work_phone'           => array('title'=>_PHONE, 'type'=>'label'),
				'work_mobile_phone'    => array('title'=>_MOBILE_PHONE, 'type'=>'label'),
				'default_visit_price'  => array('title'=>_DEFAULT_PRICE_PER_VISIT, 'type'=>'label', 'pre_html'=>$pre_currency_symbol.' ', 'post_html'=>$post_currency_symbol),
				'default_visit_duration' => array('title'=>_DEFAULT_VISIT_DURATION, 'type'=>'enum', 'source'=>$arr_slots),
				'is_active'            => array('title'=>_ACTIVE, 'type'=>'enum', 'source'=>$arr_activity),
			),			
			'separator_personal_info'   =>array(
				'separator_info' => array('legend'=>_PERSONAL_INFORMATION),
				'first_name'   => array('title'=>_FIRST_NAME, 'type'=>'label'),
				'middle_name'  => array('title'=>_MIDDLE_NAME, 'type'=>'label'),
				'last_name'    => array('title'=>_FIRST_NAME, 'type'=>'label'),
				'gender'       => array('title'=>_GENDER, 'type'=>'enum', 'source'=>$arr_genders),
				'birth_date'   => array('title'=>_BIRTH_DATE, 'type'=>'date', 'format'=>'date', 'format_parameter'=>$date_format),
				'title'        => array('title'=>_TITLE, 'type'=>'enum', 'source'=>$arr_titles),
			),
			'separator_professional_info'   =>array(
				'separator_info'        => array('legend'=>_PROFESSIONAL_INFORMATION),
				'medical_degree'        => array('title'=>_DEGREE, 'type'=>'enum', 'source'=>$arr_degrees),
				'education'             => array('title'=>_EDUCATION, 'type'=>'label'),
				'residency_training'    => array('title'=>_RESIDENCY_TRAINING, 'type'=>'label'),
				'hospital_affiliations' => array('title'=>_HOSPITAL_AFFILIATIONS, 'type'=>'label'),
				'board_certifications'  => array('title'=>_BOARD_CERTIFICATIONS, 'type'=>'label'),
				'awards_and_publications' => array('title'=>_AWARDS_AND_PUBLICATIONS, 'type'=>'label'),
				'languages_spoken'      => array('title'=>_LANGUAGES_SPOKEN, 'type'=>'label'),
				'insurances_accepted'   => array('title'=>_INSURANCES_ACCEPTED, 'type'=>'label'),
			),
		);

		///////////////////////////////////////////////////////////////////////////////
		// #004. add translation fields to all modes
		/// $this->AddTranslateToModes(
		/// $this->arrTranslations,
		/// array('name'        => array('title'=>_NAME, 'type'=>'textbox', 'width'=>'410px', 'required'=>true, 'maxlength'=>'', 'readonly'=>false),
		/// 	  'description' => array('title'=>_DESCRIPTION, 'type'=>'textarea', 'width'=>'410px', 'height'=>'90px', 'required'=>false, 'readonly'=>false)
		/// )
		/// );
		///////////////////////////////////////////////////////////////////////////////			

	}
	
	//==========================================================================
    // Class Destructor
	//==========================================================================
    function __destruct()
	{
		// echo 'this object has been destroyed';
    }


	//==========================================================================
    // MicroGrid Methods
	//==========================================================================	
	/**
	 *	After-deleting record
	 */
	public function AfterDeleteRecord()
	{
		// clean schedule timeblocks table		
		$sql = 'DELETE FROM '.TABLE_SCHEDULE_TIMEBLOCKS.'
				WHERE schedule_id IN (SELECT id FROM '.TABLE_SCHEDULES.' WHERE doctor_id = '.(int)$this->curRecordId.')';
		database_void_query($sql);
		
		// clean schedules		
		$sql = 'DELETE FROM '.TABLE_SCHEDULES.' WHERE doctor_id = '.(int)$this->curRecordId;
		database_void_query($sql);

		// clean spesialities		
		$sql = 'DELETE FROM '.TABLE_DOCTORS_SPECIALITIES.' WHERE doctor_id = '.(int)$this->curRecordId;
		database_void_query($sql);
	}

	//==========================================================================
    // Static Methods
	//==========================================================================
	/**
	 *	Returns all array of all active languages
	 *		@param $where_clause
	 */
	public static function GetAllActive($where_clause = '')
	{		
		$sql = 'SELECT * FROM '.TABLE_DOCTORS.'
				WHERE is_active = 1 '.(($where_clause != '') ? ' AND '.$where_clause : '').'
				ORDER BY id ASC';					
		return database_query($sql, DATA_AND_ROWS);
	}
	
	/**
	 *	Returns doctor's info by schedule
	 *		@param $schedule_id
	 */
	public static function GetDoctorInfoBySchedule($schedule_id = '')
	{		
		$sql = 'SELECT d.*
				FROM '.TABLE_DOCTORS.' d
					INNER JOIN '.TABLE_SCHEDULES.' sch ON d.id = sch.doctor_id
				WHERE sch.id = '.(int)$schedule_id;				
		return database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY);
	}	

	/**
	 *	Returns doctor's info by ID
	 *		@param $doctor_id
	 */
	public static function GetDoctorInfoById($doctor_id = '')
	{		
		$sql = 'SELECT * FROM '.TABLE_DOCTORS.' WHERE id = '.(int)$doctor_id;				
		return database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY);
	}	
	
	/**
	 *	Draw appointments block on homepage
	 *		@param $draw
	 */
	public static function DrawAppointmentsBlock($draw = true)
	{
		$sel_specialities = isset($_POST['sel_specialities']) ? prepare_input($_POST['sel_specialities']) : '';
		$doctor_name = isset($_POST['doctor_name']) ? prepare_input($_POST['doctor_name']) : '';
		$search_type = isset($_POST['search_type']) ? prepare_input($_POST['search_type']) : 'by_speciality';
		
		$output = '	
		<form action="index.php?page=find_doctors" id="frmFindDoctors" name="frmFindDoctors" method="post">
		'.draw_hidden_field('p', '1', false, 'page_number').'
		'.draw_hidden_field('start_day', date('Y-m-d'), false, 'start_day').'
		'.draw_token_field(false).'
			<table cellspacing="1" border="0">
			<tr valign="middle">
				<td width="16px">
					<input type="radio" class="radio" id="search_type_by_speciality" name="search_type" value="by_speciality"'.(($search_type == 'by_speciality') ? ' checked="checked"' : '').'>
				</td>
				<td>
					<label for="search_type_by_speciality">'._FIND_DOCTOR_BY_SPECIALITY.'</label>
				</td>
			</tr>
			<tr>
				<td colspan="2">
					<select name="sel_specialities" onchange="appSetChecked(\'search_type_by_speciality\')">
						<option value="">-- '._SELECT.' --</option>';											
						$total_specialities = Specialities::GetAllActive();
						foreach($total_specialities[0] as $key => $val){
							$selected = (($search_type == 'by_speciality' && $val['id'] == $sel_specialities) ? ' selected="selected"' : '');
							$output .= '<option value="'.$val['id'].'"'.$selected.'>'.$val['name'].'</option>';
						}					
					$output .= '					
					<select>				
				</td>
			</tr>
			<tr><td colspan="2"></td></tr>
			<tr valign="middle">
				<td>
					<input type="radio" class="radio" id="search_type_by_name" name="search_type" value="by_name"'.(($search_type == 'by_name') ? ' checked="checked"' : '').'> 
				</td>
				<td>
					<label for="search_type_by_name">'._FIND_DOCTOR_BY_NAME.'</label>
				</td>
			</tr>
			<tr>				
				<td colspan="2">
					<input type="text" name="doctor_name" value="'.(($search_type == 'by_name') ? $doctor_name : '').'" maxlength="64">
				</td>
			</tr>
			<tr><td colspan="2" nowrap style="height:2px"></td></tr>
			<tr>
				<td colspan="2">
					<input class="button" type="button" onclick="appFormSubmit(\'frmFindDoctors\')" value="'._FIND_DOCTORS.'" />
				</td>
			</tr>	
			</table>
		</form>';
		
		if($draw) echo $output;
		else return $output;
	}
	
	/**
	 *	Draw appointments block on homepage
	 *		@param $search_type
	 *		@param $speciality
	 *		@param $doctor_name
	 */
	public static function SearchFor($search_type = 'by_speciality', $search_string = '')
	{
		$result = array();
		if($search_type == 'by_speciality'){
			$total_doctors = DoctorsSpecialities::GetDoctorsBySpeciality($search_string);
		}else{
			$total_doctors = DoctorsSpecialities::GetDoctorsByName($search_string);			
		}

		foreach($total_doctors[0] as $key => $val){
			$result[$val['doctor_id']] = array(
				'first_name'=>$val['first_name'],
				'middle_name'=>$val['middle_name'],
				'last_name'=>$val['last_name'],
				'title'=>$val['title'],
				'gender'=>$val['gender'],
				'medical_degree'=>$val['medical_degree'],
				'doctor_photo'=>$val['doctor_photo'],
				'doctor_photo_thumb'=>$val['doctor_photo_thumb'],
				'speciality'=>$val['speciality_name']
			);
		}								
		
		return $result;		
	}

	/**
	 *	Draw appointments block on homepage
	 *      @param $result
	 *      @param $search_type
	 *      @param $speciality
	 *		@param $draw
	 */
	public static function DrawSearchResult($result, $search_type = 'by_speciality', $speciality = '', $draw = true)
	{
		$output = '';
		$start_day = isset($_POST['start_day']) ? prepare_input($_POST['start_day']) : date('Y-m-d');
		$is_active = ModulesSettings::Get('appointments', 'is_active');

		$search_page_size = "20";
		$doctors_total = count($result);
		
		// -------- pagination		
		$current_page = isset($_REQUEST['p']) ? (int)$_REQUEST['p'] : "1";
		$total_pages = (int)($doctors_total / $search_page_size);		
		if($current_page > ($total_pages+1)) $current_page = 1;
		if(($doctors_total % $search_page_size) != 0) $total_pages++;
		if(!is_numeric($current_page) || (int)$current_page <= 0) $current_page = 1;
		// --------
		
		if(empty($result)){
			if($search_type == 'by_speciality'){
				$output = draw_important_message(_NO_DOCTORS_FOUND_IN_SPEC, false);	
			}else{
				$output = draw_important_message(_NO_DOCTORS_FOUND, false);	
			}			
		}else{		
			// prepare array for next 7 days
			$current_day = strtotime($start_day);
			$arr_dates = array();
			for($i=0; $i<7; $i++){
				$current_date = ($i == 0) ? $current_day : strtotime('+'.$i.' day', $current_day); 					
				$arr_dates[] = array(
					'date'=>date('Y-m-d', $current_date),
					'date_view'=>format_date(date('Y-m-d', $current_date)),
					'week_day_num'=>(date('w', $current_date)+1),
					'week_day'=>get_weekday_local(date('w', $current_date)+1)
				);				
			}
			$prev_week_day = date('Y-m-d', strtotime('-6 day', $current_day)); 					
			$next_week_day = date('Y-m-d', strtotime('+6 day', $current_day));
			
			$but_prev = (Application::Get('lang_dir') == 'ltr') ? 'but_prev' : 'but_next';
			$but_next = (Application::Get('lang_dir') == 'ltr') ? 'but_next' : 'but_prev';
			
			$output .= '<table class="doctors_result">';
			$output .= '
				<tr valign="top">
					<td width="100px">'._DOCTORS.'</td>';
					if($is_active == 'yes'){
						$output .= '<td align="right" valign="middle">';
									if($prev_week_day >= date('Y-m-d')){
										$output .= '<a href="javascript:void(\'week|previous\');" title="'._PREVIOUS.'" onclick="appFormSubmit(\'frmFindDoctors\',\'start_day='.$prev_week_day.'&page_number='.$current_page.'\')"><img src="templates/'.Application::Get("template").'/images/'.$but_prev.'_active.png"></a>';
									}else{
										$output .= '<img src="templates/'.Application::Get("template").'/images/'.$but_prev.'.png">';
									}								
						$output .= '</td>';						
						$output .= '<td>';
							$output .= '<table width="100%"><tr>';
							$days_count = 0;
							foreach($arr_dates as $dkey => $dval){
								$background_color = ($days_count++ % 2 == 0) ? '#f9f4ed' : '#ffffff';
								$output .= '<td style="background-color:'.$background_color.'" align="center">'.$dval['week_day'].'<br>'.$dval['date_view'].'</td>';
							}
							$output .= '<td valign="middle">
										<a href="javascript:void(\'week|next\');" title="'._NEXT.'" onclick="appFormSubmit(\'frmFindDoctors\',\'start_day='.$next_week_day.'&page_number='.$current_page.'\')"><img src="templates/'.Application::Get("template").'/images/'.$but_next.'_active.png"></a>
										</td>';						
							$output .= '</tr></table>';
						$output .= '</td>';
					}
				$output .= '</tr>';

			$doctors_count = 0;
			foreach($result as $key => $val){
				$doctors_count++;
				
				if($doctors_count <= ($search_page_size * ($current_page - 1))){
					continue;
				}else if($doctors_count > ($search_page_size * ($current_page - 1)) + $search_page_size){
					break;
				}
				
				$photo = ($val['doctor_photo_thumb'] != '') ? $val['doctor_photo_thumb'] : 'doctor_'.$val['gender'].'.png';
				$output .= '
					<tr valign="top">
						<td width="100px">
							<img class="doctor_photo" src="images/doctors/'.$photo.'" width="88px" height="88px">
						</td>
						<td>
							'.prepare_permanent_link('index.php?page=doctor_info&docid='.(int)$key, $val['title'].' '.$val['first_name'].' '.$val['middle_name'].' '.$val['last_name']).'<br>
							'.$val['medical_degree'].'<br>
							'.$val['speciality'].'
						</td>';
					if($is_active == 'yes'){
						$output .= '<td>';
							$output .= '<table width="100%"><tr>';
							$days_count = 0;
							foreach($arr_dates as $dkey => $dval){
								$background_color = ($days_count++ % 2 == 0) ? '#f9f4ed' : '#ffffff';
								$time_slots = ScheduleTimeblocks::GetTimeSlotsForDay($key, $dval['date'], $dval['week_day_num']);
								$slots = 0;
								$output .= '<td style="width:50px;background-color:'.$background_color.'" align="center" valign="top">';
								foreach($time_slots as $ts_key => $ts_val){
									$output .= prepare_permanent_link('index.php?page=appointment_details&docid='.$key.'&dspecid='.$speciality.'&schid='.$ts_val['schedule_id'].'&date='.$dval['date'].'&start_time='.$ts_val['time'].'&duration='.$ts_val['duration'], $ts_val['time_view']).'<br>'."\n";
									if($slots == 5){
										$output .= '<div class="hidden_slots'.$key.'" style="display:none;">';
									}
									$slots++;
								}
								if($slots > 6){
									$output .= '</div>';
									$output .= '<a class="more_links'.$key.'" href="javascript:void(0)" onclick="appShowElement(\'.hidden_slots'.$key.'\');appHideElement(\'.more_links'.$key.'\');">'._MORE.'...</a>';
								}
								$output .= '</td>';								
							}
							$output .= '<td width="12px" nowrap></td>';						
							$output .= '</tr></table>';						
						$output .= '</td>';
					}
					$output .= '</tr>';
				$output .= '<tr valign="top"><td colspan="3"><hr></td></tr>';
			}
			$output .= '</table>';
			
			$output .= "<div class='paging'>";
			for($page_ind = 1; $page_ind <= $total_pages; $page_ind++){
				$output .= "<a class='paging_link' href=\"javascript:void('page|".$page_ind."');\" onclick=\"javascript:appFormSubmit('frmFindDoctors','page_number=".$page_ind."')\">".(($page_ind == $current_page) ? "<b>[".$page_ind."]</b>" : $page_ind)."</a> ";
			}
			$output .= "</div>"; 
		}

		if($draw) echo $output;
		else return $output;
	}
	
	/**
	 *	Draw appointments block on homepage
	 *      @param $doctor_id
	 *		@param $draw
	 */
	public static function DrawDoctorInfo($doctor_id, $draw = true)
	{
		$output = '';		
		
		$result = Doctors::GetAllActive('id = '.(int)$doctor_id);
		if($result[1] > 0){
			$photo = ($result[0][0]['doctor_photo'] != '') ? $result[0][0]['doctor_photo'] : 'doctor_'.$result[0][0]['gender'].'.png';
			$doctor_name = $result[0][0]['first_name'].' '.$result[0][0]['middle_name'].' '.$result[0][0]['last_name'];
			$title = ($result[0][0]['title'] != '') ? $result[0][0]['title'] : '';			
			$medical_degree = ($result[0][0]['medical_degree'] != '') ? ' - '.$result[0][0]['medical_degree'] : '';
			$education = ($result[0][0]['education'] != '') ? ' <b>'._EDUCATION.'</b>: <br>'.$result[0][0]['education'].'<br><br>' : '';
			$residency_training = ($result[0][0]['residency_training'] != '') ? ' <b>'._RESIDENCY_TRAINING.'</b>: <br>'.$result[0][0]['residency_training'].'<br><br>' : '';
			$hospital_affiliations = ($result[0][0]['hospital_affiliations'] != '') ? ' <b>'._HOSPITAL_AFFILIATIONS.'</b>: <br>'.$result[0][0]['hospital_affiliations'].'<br><br>' : '';
			$board_certifications = ($result[0][0]['board_certifications'] != '') ? ' <b>'._BOARD_CERTIFICATIONS.'</b>: <br>'.$result[0][0]['board_certifications'].'<br><br>' : '';
			$awards_and_publications = ($result[0][0]['awards_and_publications'] != '') ? ' <b>'._AWARDS_AND_PUBLICATIONS.'</b>: <br>'.$result[0][0]['awards_and_publications'].'<br><br>' : '';
			$languages_spoken = ($result[0][0]['languages_spoken'] != '') ? ' <b>'._LANGUAGES_SPOKEN.'</b>: <br>'.$result[0][0]['languages_spoken'].'<br><br>' : '';
			$insurances_accepted = ($result[0][0]['insurances_accepted'] != '') ? ' <b>'._INSURANCES_ACCEPTED.'</b>: <br>'.$result[0][0]['insurances_accepted'].'<br><br>' : '';
			$default_visit_price = ($result[0][0]['default_visit_price'] != '') ? ' <b>'._DEFAULT_PRICE_PER_VISIT.'</b>: <br>'.Currencies::PriceFormat($result[0][0]['default_visit_price']).'<br><br>' : '';
			
			$output .= '<table class="doctor_info">';		
			$output .= '<tr valign="top">';
			$output .= '<td width="128px"><img class="doctor_photo" src="images/doctors/'.$photo.'" width="120px" height="120px"></td>';
			$output .= '<td>
					<h3>'.$title.$doctor_name.$medical_degree.'</h3>
						'.$education.'
						'.$residency_training.'
						'.$hospital_affiliations.'
						'.$board_certifications.'
						'.$awards_and_publications.'
						'.$languages_spoken.'
						'.$insurances_accepted.'
						'.$default_visit_price.'
					</td>';
			$output .= '</tr>';		
			$output .= '</table>';					
		}else{
			$output .= _WRONG_PARAMETER_PASSED;					
		}
	
		if($draw) echo $output;
		else return $output;
	}

	/**
	 *	Get doctor specialities
	 *		@param $doctor_id
	 */
	public static function GetDoctorSpecialities($doctor_id = 0)
	{
		$sql = 'SELECT
					d.id as doctor_id,
					s.id as speciality_id,
					s.name as speciality_name
				FROM '.TABLE_DOCTORS_SPECIALITIES.' ds
					INNER JOIN '.TABLE_DOCTORS.' d ON ds.doctor_id = d.id
					INNER JOIN '.TABLE_SPECIALITIES.' s ON ds.speciality_id = s.id
				WHERE
					ds.doctor_id = '.(int)$doctor_id;
		return database_query($sql, DATA_AND_ROWS);
	}

	/**
	 *	Get doctor speciality
	 *		@param $doctor_id
	 *		@param $speciality_id
	 */
	public static function GetDoctorSpeciality($doctor_id = 0, $speciality_id = 0)
	{
		$sql = 'SELECT
					s.id as speciality_id,
					s.name as speciality_name
				FROM '.TABLE_DOCTORS_SPECIALITIES.' ds
					INNER JOIN '.TABLE_DOCTORS.' d ON ds.doctor_id = d.id
					INNER JOIN '.TABLE_SPECIALITIES.' s ON ds.speciality_id = s.id
				WHERE
					ds.doctor_id = '.(int)$doctor_id.' AND
					ds.speciality_id = '.(int)$speciality_id;
		return database_query($sql, DATA_AND_ROWS, FIRST_ROW_ONLY);
	}

}
?>